import {DeviceEventEmitter} from 'react-native';
import {STORE} from '../type';
import axios from 'axios';
import Tips from 'react-native-root-tips';
import { ToastAndroid } from 'react-native';

// 获取搜索到的商品列表
const getStoreList = (text, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });

    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/getProductsByCredentials', {
        params: {
            shop_id: clerkInfo.shop_id || '',
            keyword: text
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: STORE.SEARCH_GOODS_LIST,
                    res: res.data
                })
            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 获取商品SKU信息
const getGoodsSku = (id, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});

    const res = await axios.get('api/v2/shop/getStockByID/' + id, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (!res.data || !res.data.specs) return res;
            
            // 规格
            if (res.data.specs) {
                let specs = [];
                Object.keys(res.data.specs)
                    .forEach((key, index) => {
                        let value = res.data.specs[key];
                        value.select = '';
                        value.values = value.list
                            .map(v => {
                                return Object.assign({
                                    index: index,
                                    active: false,
                                    disabled: false
                                }, v);
                            });
                        delete value.list;
                        specs.push(value);
                    });
                dispatch({
                    type: STORE.SKU_INFO,
                    res: specs
                })
            }

            // 数量
            if (res.data.stores) {
                let data = {};
                Object.keys(res.data.stores)
                    .forEach(key => {
                        let value = res.data.stores[key];

                        value.ids.forEach(id => {
                            data[id] = data[id] || {count: 0, specs: {}};
                            data[id].count += parseInt(value.store);

                            value.ids.forEach(i => {
                                if (i === id) return res;

                                data[id].specs[i] = {
                                    count: parseInt(value.store)
                                };
                            });
                        });
                    });
                const result = {data, table: res.data.stores};
                dispatch({
                    type: STORE.SPEC_STORE,
                    res: result
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    callback && callback(res);
};

// 提交订单
const submitOrder = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});

    const res = await axios.post('api/v2/shop/order/checkout', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            storage.save({
                key: 'order-info',
                data: res.data
            });
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    callback && callback(res);
};

// 获取导购列表
const getClerkList = (callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/clerk/list', {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: STORE.CLERK_LIST,
                    res: res.data
                })
            } else {
                dispatch({
                    type: STORE.CLERK_LIST,
                    res: []
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 获取店铺列表
const getShopList = (callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/getQueryFields', {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: STORE.SHOP_LIST,
                    res: res.data
                })
            } else {
                dispatch({
                    type: STORE.SHOP_LIST,
                    res: []
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 提交订单
const confirmOrder = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/order/confirm', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

//获取订单列表
const getOrderList = (page,user_id,order_no, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/order/list', {
        params: {
            page:page,
            user_id: user_id,
            order_no: order_no
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let hasMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['orderList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.ORDER_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('orderHasMore',hasMore);
            } else {
                ToastAndroid.showWithGravity('未搜索到订单', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 获取订单详情
const getOrderDetail = (order_no,callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});

    dispatch({
        type: STORE.ORDER_DETAIL,
        res: ''
    });

    const res = await axios.get('api/v2/shop/order/detail/'+order_no, {

    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                /*let items = res.data.order.items;
                items.forEach(item => {
                    item.isChecked = false
                });
                console.log('循环他',items);*/
                dispatch({
                    type: STORE.ORDER_DETAIL,
                    res: res.data
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 提交充值订单
const submitBalanceOrder = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});

    const res = await axios.post('api/v2/shop/balance/order/checkout', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            storage.save({
                key: 'balance-order-info',
                data: res.data
            });
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    callback && callback(res);
};

// 提交充值订单
const confirmBalanceOrder = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/balance/order/paid', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 获取充值订单详情
const getBalanceOrderDetail = (order_no,callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    dispatch({
        type: STORE.ORDER_BALANCE_DETAIL,
        res: ''
    });

    console.log('这个应该是跑了的');
    const res = await axios.get('api/v2/shop/balance/order/detail/'+order_no, {
        headers: {
            Authorization: token
        }

    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: STORE.ORDER_BALANCE_DETAIL,
                    res: res.data
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};
//获取充值订单列表
const getBalanceOrderList = (page,user_id,order_no, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/balance/order/list', {
        params: {
            page:page,
            user_id: user_id,
            order_no: order_no
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let hasMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['orderBalanceList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.ORDER_BALANCE_LIST,
                    res: list
                })
                DeviceEventEmitter.emit('orderBalanceHasMore',hasMore);
            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};
// 获取库存查询列表
const getStockList = (page, shop_id, years_id, season_id, category_id, brand_id, is_checked, text, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });

    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/goods/stock/query', {
        params: {
            searchKey: text,
            page:page,
            category_id: category_id || '',
            season_id: season_id || '',
            years_id: years_id || '',
            brand_id: brand_id || '',
            shop_id: shop_id || clerkInfo.shop_id ,
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                if (is_checked) {
                    dispatch({
                        type: STORE.STOCK_LIST,
                        res: []
                    })
                }
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['stockList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.STOCK_LIST,
                    res: list
                })
                DeviceEventEmitter.emit('stockHasMore',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.STOCK_LIST,
                    res: []
                })
                ToastAndroid.showWithGravity('未搜索到商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

//确认添加新增数据
const addCash = (data,callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/cash/record/store', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            //添加成功之后

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

//获取现金收支列表
const getCashList = (page,time, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/cash/record/list', {
        params: {
            page:page,
            time:time
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let hasMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['cashList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.CASH_LIST,
                    res: list
                })
                DeviceEventEmitter.emit('cashHasMore',hasMore, res.meta);
            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};


// 获取积分使用比例以及上限值
const getPointProportion = (callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    const res = await axios.get('api/v2/shop/point/proportion', {
        params: {
            shop_id: clerkInfo.shop_id || '',
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            dispatch({
                type: STORE.POINT_PROPORTION,
                res: res.data
            })
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};


// 获取折扣信息
const getDiscountInfo = (callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });

    dispatch({
        type: STORE.DISCOUNT_INFO,
        res: ''
    });
    const res = await axios.get('api/v2/shop/discount', {
        params: {
            shop_id: clerkInfo.shop_id || '',
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let disList = [];  // 整理好的促销列表
                const disType = res.data[0].action_type.type; // 获取第一个促销的类型，其他的促销应该跟第一个相同。只能同时存在一种促销
                /*
                disType：
                type = cash 减钱
                type = discount 打折

                actions中type值代表的意思：
                order_fixed_discount    订单减钱
                goods_fixed_discount    商品减钱
                order_percentage_discount   订单折扣
                goods_percentage_discount   商品折扣
                */
                res.data.forEach(item => {
                    item.isActive = false;
                    item.disTotalAmount = 0;  // 当前优惠券能抵扣多少钱
                   /*if (item.action_type.type == disType) {
                       disList.push(item)
                   }*/
                    disList.push(item)
                });
                console.log('这个是处理后的', disList);
                dispatch({
                    type: STORE.DISCOUNT_INFO,
                    res: disList
                })
            } else {
                dispatch({
                    type: STORE.DISCOUNT_INFO,
                    res: []
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};


// 获取默认用户信息
const getSystemUser = (callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    const res = await axios.get('api/v2/shop/getSystemUser', {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 申请售后
const submitAfterSale = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});

    const res = await axios.post('api/v2/shop/refund/apply', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            storage.save({
                key: 'refund-data',
                data: res.data
            });
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};



// 提交售后申请
const submitRefund = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});

    const res = await axios.post('api/v2/shop/refund/checkout', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            storage.save({
                key: 'refund-order-info',
                data: res.data
            });
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 提交售后订单
const confirmRefundOrder = (data, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/refund/confirm', data, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};


// 售后成功信息
const refundSuccessInfo = (id, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/refund/refundSuccess', {
        params: {
            refund_id: id
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

const getPrintInfo = (order_no, callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('/api/v2/shop/print', {
        params: {
            order_no: order_no
        }

    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    console.log('666', res);
    callback && callback(res);
};

const getRefundPrintInfo = (refund_id, callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('/api/v2/shop/print/refund', {
        params: {
            refund_id: refund_id
        }

    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    console.log('666', res);
    callback && callback(res);
};
// 根据条码获取商品
const getProductByScanSku = (text, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });

    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/getProductByScanSku', {
        params: {
            shop_id: clerkInfo.shop_id || '',
            sku: text
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {

            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 扫码入库
const getProductData = (text,type, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });

    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getProductData', {
        params: {
            shop_id: clerkInfo.shop_id || '',
            sku: text,
            type: type
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {

            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }

        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 提交采购数据
const confirmProductData = (data,type,remark, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/warehouse/purchase', {
        goods: data,
        type: type,
        remark: remark
    }, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 获取历史记录
const getPurchaseData = (type,page, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getPurchaseData', {
        params: {
            type: type,
            page: page
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['productDataHistoryList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.PRODUCT_DATA_HISTORY_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('isLoadMorePurchaseData',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.PRODUCT_DATA_HISTORY_LIST,
                    res: []
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 获取历史记录详情
const getPurchaseDetailData = (id,page, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getPurchaseItem', {
        params: {
            id: id,
            page: page
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['productDataHistoryDetailList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.PRODUCT_DATA_HISTORY_DETAIL_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('isLoadMorePurchaseItem',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.PRODUCT_DATA_HISTORY_DETAIL_LIST,
                    res: []
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 扫码盘点
const getInventoryData = (text,plan_id, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });

    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTakeProductData', {
        params: {
            plan_id: plan_id,
            sku: text
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {

            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }

        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 手动输入扫码盘点
const getInputInventoryData = (text,plan_id, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });

    const clerkInfo = await storage.load({
        key: 'clerk-info'
    }).then(res => {
        if (res) {
            console.log(res);
            return res
        }
    }).catch(err => {

    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTakeProductDataByCode', {
        params: {
            plan_id: plan_id,
            sku: text
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {

            } else {
                ToastAndroid.showWithGravity('未搜索到相关商品', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        } else {
            Tips.showFail(res.message || '请求失败')
        }

        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);

};

// 获取盘点方案列表
const getInventoryPlanList = (callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTakePlans', {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 提交盘点数据
const confirmInventoryData = (data,plan_id,remark, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/warehouse/saveTakeStock', {
        goods: data,
        plan_id: plan_id,
        remark: remark
    }, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 库存盘点历史记录
const getTakeList = (page, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTakeList', {
        params: {
            page: page
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['inventoryHistoryList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.INVENTORY_HISTORY_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('isLoadMoreInventoryHistoryList',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.INVENTORY_HISTORY_LIST,
                    res: []
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 库存盘点历史记录详情
const getTakeItems = (id,page, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTakeItems', {
        params: {
            id: id,
            page: page
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['inventoryHistoryDetailList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.INVENTORY_HISTORY_DETAIL_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('isLoadMoreInventoryHistoryDetailList',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.INVENTORY_HISTORY_DETAIL_LIST,
                    res: []
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 提交调拨数据
const confirmTransferData = (data,type,in_shop_id, remark, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/warehouse/TransferController', {
        goods: data,
        type: type,
        in_shop_id: type == 'transfer_in' ? '' : in_shop_id,
        remark: remark
    }, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {

        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 库存调拨历史记录
const getTransferList = (page, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTransferList', {
        params: {
            page: page
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['transferHistoryList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.TRANSFER_HISTORY_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('isLoadMoreTransferHistoryList',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.TRANSFER_HISTORY_LIST,
                    res: []
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 库存调拨历史记录详情
const getTransferItem = (id,page, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/getTransferItem', {
        params: {
            id: id,
            page: page
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['store']['transferHistoryDetailList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: STORE.TRANSFER_HISTORY_DETAIL_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('isLoadMoreTransferHistoryDetailList',isLoadMore, res.meta);
            } else {
                dispatch({
                    type: STORE.TRANSFER_HISTORY_DETAIL_LIST,
                    res: []
                });
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

// 库存调拨确认收货
const transferConfirm = (id,index, callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        console.log(res);
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/warehouse/transferConfirm', {
        params: {
            id: id,
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            let stateList = getState()['store']['transferHistoryList'];
            let item = stateList[index];
            item.status = 1;
            dispatch({
                type: STORE.TRANSFER_HISTORY_LIST,
                res: stateList
            });
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};

export default {
    getStoreList,
    getGoodsSku,
    submitOrder,
    getClerkList,
    confirmOrder,
    getOrderDetail,
    getOrderList,
    submitBalanceOrder,
    confirmBalanceOrder,
    getBalanceOrderDetail,
    getBalanceOrderList,
    getStockList,
    getPointProportion,
    addCash,
    getCashList,
    getDiscountInfo,
    getSystemUser,
    submitAfterSale,
    submitRefund,
    confirmRefundOrder,
    refundSuccessInfo,
    getPrintInfo,
    getRefundPrintInfo,
    getShopList,
    getProductByScanSku,
    getProductData,
    getInventoryData,
    getInputInventoryData,
    confirmProductData,
    confirmInventoryData,
    getInventoryPlanList,
    confirmTransferData,
    getPurchaseData,
    getPurchaseDetailData,
    getTakeList,
    getTakeItems,
    getTransferList,
    getTransferItem,
    transferConfirm
}